package timethingy.backend.impl.sqlite;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class SqliteConnectionHandler {

	private static SqliteConnectionHandler instance = null;

	public static SqliteConnectionHandler getConnectionHandler() {
		if(instance == null)
			instance = new SqliteConnectionHandler();
		
		return instance;
	}
	
	// TODO: default location and shit
	protected SqliteConnectionHandler(){
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Connection conn = null;
	
	public boolean closeDb(){
		try{
			if(conn != null && !conn.isClosed()){
				conn.close();
			}
		} catch(SQLException ex){
			ex.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	public boolean openDb(String location){
		try{
			conn = DriverManager.getConnection("jdbc:sqlite:" + location);
		} catch(SQLException ex) {
			ex.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean changeDb(String location){
		return closeDb() && openDb(location);
	}
		
	public void executeUpdate(String stmt) throws SQLException{
		if(conn.isValid(0)){
			Statement statement = conn.createStatement();
			statement.executeUpdate(stmt);
		} else {
			throw new SQLException("connection is not available!");
		}
	}
	
	public PreparedStatement getPreparedStatement(String stmt) throws SQLException {
		if(conn.isValid(0))
			return conn.prepareStatement(stmt);
		else
			throw new SQLException("connection is not available!");
	}
}
